package com.example.gokuplayalong.service.publicclient.interceptor;


import com.alibaba.fastjson.JSONObject;
import com.example.gokuplayalong.bases.base.ExceptionHandler;
import com.example.gokuplayalong.bases.mysql.MysqlDruid;
import com.example.gokuplayalong.bases.security.Communication;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Objects;
import java.util.concurrent.Semaphore;

public class PublicHandlerInterceptor {
    static PublicHandlerInterceptor INSTANCE = null;

    static Semaphore semaphore = new Semaphore(1);

    public static PublicHandlerInterceptor getInstance() {
        if (INSTANCE == null) INSTANCE = new PublicHandlerInterceptor();
        return INSTANCE;
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        try {
          //  System.out.println(request.getHeader("Token"));
            Connection conn = MysqlDruid.dataSource.getConnection();
            PreparedStatement pstmt = conn.prepareStatement("select * from profileinfo");
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                if (Objects.equals(rs.getString("token"), request.getHeader("Token"))) {
                    if (conn != null && !conn.isClosed()) conn.close();
                    return true;
                }
            }

            if (conn != null && !conn.isClosed()) conn.close();

            System.out.println("token failed");
            response.setContentType("text/plain");
            response.setCharacterEncoding("UTF-8");

            JSONObject msgToClient = new JSONObject();
            msgToClient.put("status", 201);
            msgToClient.put("message", "token is not correct");
            msgToClient.put("result", "失败");

            response.getWriter().println(new Communication().MessageEncrypt(msgToClient.toJSONString()));

        } catch (Throwable e) {
            ExceptionHandler.saveException(Thread.currentThread().getStackTrace()[1].getClassName() + Thread.currentThread().getStackTrace()[1].getMethodName() + Thread.currentThread().getStackTrace()[1].getLineNumber(), e);
        }

        return false;
    }
}
